<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use service\WordService;
use think\App;
use think\Db;

/**
 * 后台入口
 * Class Index
 * @package app\admin\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/02/15 10:41
 */
class Index extends BasicAdmin
{

    /**
     * 后台框架布局
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        NodeService::applyAuthNode();
        $list = (array)Db::name('SystemMenu')->where(['status' => '1'])->order('sort asc,id asc')->select();
        $menus = $this->buildMenuData(ToolsService::arr2tree($list), NodeService::get(), !!session('user'));
        if (empty($menus) && !session('user.id')) {
            $this->redirect('@admin/login');
        }

        return $this->fetch('', ['title' => '系统管理', 'menus' => $menus]);
    }
    public function readDoc(){
        $ws = new WordService();
        echo $ws->readDocument('C:\Users\Administrator\Desktop\1.docx');
    }
    /**
     * 后台主菜单权限过滤
     * @param array $menus 当前菜单列表
     * @param array $nodes 系统权限节点数据
     * @param bool $isLogin 是否已经登录
     * @return array
     */
    private function buildMenuData($menus, $nodes, $isLogin)
    {
        foreach ($menus as $key => &$menu) {
            !empty($menu['sub']) && $menu['sub'] = $this->buildMenuData($menu['sub'], $nodes, $isLogin);
            if (!empty($menu['sub'])) {
                $menu['url'] = '#';
            } elseif (preg_match('/^https?\:/i', $menu['url'])) {
                continue;
            } elseif ($menu['url'] !== '#') {
                $node = join('/', array_slice(explode('/', preg_replace('/[\W]/', '/', $menu['url'])), 0, 3));
                $menu['url'] = url($menu['url']);
                if (isset($nodes[$node]) && $nodes[$node]['is_login'] && empty($isLogin)) {
                    unset($menus[$key]);
                } elseif (isset($nodes[$node]) && $nodes[$node]['is_auth'] && $isLogin && !auth($node)) {
                    unset($menus[$key]);
                }
            } else {
                unset($menus[$key]);
            }
        }
        return $menus;
    }

    /**
     * 主机信息显示
     * @return string
     */
    public function main()
    {
        //循环查询
        $db = Db::name('formula')->alias("f");
        $db->join("formula_attr f1","f1.pid = f.id");
        $searchattr = array();
        $tagsArr = array();
        if(isset($_GET['attrs_id'])){
            if(!empty($_GET['attrs_id'])){
                $attrsArr = $_GET['attrs_id'];
                $db->where("f1.attr","in",$attrsArr);
                $searchattr = Db::name('system_attribute')->whereIn("id",$attrsArr)->select();
                $tagsArr = explode(",",$attrsArr);
            }
        }

        if(isset($_GET['seacrch'])){
            if(!empty($_GET['seacrch'])){

                $seacrch = $_GET['seacrch'];

                $db->where("f.name","like","%".$seacrch."%");

                $idArra =  Db::name("system_attribute")->whereLike("name","%".$seacrch."%")->column("id");
                implode(",",$idArra);
                $db->whereOr("f1.attr","in",$idArra);

            }
        }
        $idArr = $db->group("f.id")->column("f.id");
        $ids = implode(",",$idArr);
        $dbs = Db::name('formula')->where("id","in",$ids);

        $res1 = Db::name('system_category')->field("id, pid as pId, name")->cache(true,600)->select();
        $category = json_encode($res1, true);
        $res2 = Db::name('system_attribute')->field("id, pid as pId, name")->cache(true,600)->select();
        $attr = json_encode($res2, true);

        $this->assign("category", $category);
        $this->assign("attribute", $attr);
        $this->assign("searchattr", $searchattr);
        $this->assign("tagsArr", json_encode($tagsArr));
        return parent::_list($dbs);

//        $cate = Db::name('system_attribute')->where(array('pid' => 0))->select();
//        foreach ($data as $key => &$item) {
//            foreach ($cate as $key2 => &$item2) {
//                $nameArr = Db::name("formula_attr")->where(['cid' => $item2['id'], 'pid' => $item['id']])->column("attrname");
//                $name = implode(",", $nameArr);
//                $item['value'][$key2] = $name;
//            }
//        }
//        $this->assign('category', $cate);
//        $this->assign('fdata', $result['list']);
//        $this->assign('page', $result['page']);
    }

    /**
     * 主机信息显示
     * @return string
     */
    public function getProudut()
    {
        //循环查询
        $db = Db::name('formula')->alias("f");
        $db->join("formula_attr f1","f1.pid = f.id");

        if(isset($_POST['attrs_id'])){
            if(!empty($_POST['attrs_id'])){
                $attrsArr = $_POST['attrs_id'];
                $db->where("f1.attr","in",$attrsArr);
            }
        }
        if(isset($_POST['seacrch'])){
            if(!empty($_POST['seacrch'])){
                $seacrch = $_POST['seacrch'];
                $db->where("f.name","like","%".$seacrch."%");
            }
        }
        $idArr = $db->group("f.id")->column("f.id");
        $ids = implode(",",$idArr);

        $dbs = Db::name('formula')->where("id","in",$ids);
        $row_page = $this->request->get('rows', cookie('rows'), 'intval');
        cookie('rows', $row_page >= 10 ? $row_page : 20);
        $page = $dbs->paginate($row_page, true, ['query' => $this->request->get()]);

        $result['list'] = $page->all();
        $result['page'] = preg_replace(['|href="(.*?)"|', '|pagination|'], ['data-load="$1" href="javascript:void(0);"', 'pagination pull-right'], $page->render());
        print_r($result['page'] );
//        $cate = Db::name('system_attribute')->where(array('pid' => 0))->select();
//        foreach ($data as $key => &$item) {
//            foreach ($cate as $key2 => &$item2) {
//                $nameArr = Db::name("formula_attr")->where(['cid' => $item2['id'], 'pid' => $item['id']])->column("attrname");
//                $name = implode(",", $nameArr);
//                $item['value'][$key2] = $name;
//            }
//        }
//        $this->assign('category', $cate);
        $this->assign('fdata', $result['list']);
        $this->assign('page', $result['page']);
        return view("searchAttr");
    }
    /**
     * 修改密码
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pass()
    {
        if (intval($this->request->request('id')) !== intval(session('user.id'))) {
            $this->error('只能修改当前用户的密码！');
        }
        if ($this->request->isGet()) {
            $this->assign('verify', true);
            return $this->_form('SystemUser', 'user/pass');
        }
        $data = $this->request->post();
        if ($data['password'] !== $data['repassword']) {
            $this->error('两次输入的密码不一致，请重新输入！');
        }
        $user = Db::name('SystemUser')->where('id', session('user.id'))->find();
        if (md5($data['oldpassword']) !== $user['password']) {
            $this->error('旧密码验证失败，请重新输入！');
        }
        if (DataService::save('SystemUser', ['id' => session('user.id'), 'password' => md5($data['password'])])) {
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    /**
     * 修改资料
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info()
    {
        if (intval($this->request->request('id')) === intval(session('user.id'))) {
            return $this->_form('SystemUser', 'user/form');
        }
        $this->error('只能修改当前用户的资料！');
    }

}
